//
//  APPTools.m
//  TableView&CollectionView
//
//  Created by 何欣 on 15/12/18.
//  Copyright © 2015年 何欣. All rights reserved.
//

#import "APPTools.h"
#import "AFNetworking.h"


@implementation APPTools

+ (void)GETWithURL:(NSString *)urlStr
               par:(NSDictionary *)dic
           success:(void (^)(id))responseObj filed:(void (^)(NSError *))err
{
    
//    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
//    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//    NSLog(@"%@", documentPath);

    // 文件管理器
    NSFileManager *manager = [NSFileManager defaultManager];
    NSString *giftCaches = [documentPath stringByAppendingPathComponent:@"giftCaches"];
    BOOL resultFile = [manager createDirectoryAtPath:giftCaches withIntermediateDirectories:YES attributes:nil error:nil];
    if (resultFile) {
//        NSLog(@"创建缓存文件夹成功");
    }
    // 拼接缓存路径
    NSString *path = [NSString stringWithFormat:@"%ld.plist", (unsigned long) [urlStr hash]];
    NSString *textFilePath = [giftCaches stringByAppendingPathComponent:path];
    
//    // 检测网络连接的单例, 网络变化时回调方法
//    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
//        NSLog(@"网络状态 = %ld", status);
//    }];
    
    
    AFHTTPSessionManager *man = [AFHTTPSessionManager manager];
    // 有的返回的数据格式，AFN不支持解析，所以我们要设置一下。让AFN支持。
    [man.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript",nil]];
    
    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    [man GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        [netWorkManager stopMonitoring];
        
//        BOOL result = [responseObject writeToFile:textFilePath atomically:YES];
        // 归档
        [NSKeyedArchiver archiveRootObject:responseObject toFile:textFilePath];
        if ([NSKeyedArchiver archiveRootObject:responseObject toFile:textFilePath]) {
//            NSLog(@"写入成功");
        } else {
//            NSLog(@"写入失败");
        }
        
        
        responseObj(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        id result = [NSMutableDictionary dictionaryWithContentsOfFile:textFilePath];
    
        if ([NSKeyedUnarchiver unarchiveObjectWithFile:textFilePath]) {
//            NSLog(@"网络加载失败,从本地获取数据");
        }
        NSLog(@"%@", textFilePath);
        err(error);
//        responseObj(result);
        // 解档
        responseObj([NSKeyedUnarchiver unarchiveObjectWithFile:textFilePath]);
    }];
}

+ (void)POSTWithURL:(NSString *)urlStr
                par:(NSDictionary *)dic
            success:(void (^)(id))response filed:(void (^)(NSError *))err
{
    

    AFHTTPSessionManager *man = [AFHTTPSessionManager manager];
    
    [man.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript",nil]];
    
     urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    [man POST:urlStr parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        response(responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        err(error);

    }];
    
 
}




@end
